﻿using Basic.Model;
using Common.Library;
using Common.Model;
using Dapper.Library.DataAccessSql;
using Dapper.PostgreSql.Library;
using Network.Library;
using Redis.Library;
using Serialize.Library;
using System.Threading.Tasks;

namespace Basic.Logic
{
    /// <summary>
    /// 公用操作类
    /// </summary>
    public class OperationLogicImpl
    {

        /// <summary>
        /// 添加日志记录
        /// </summary>
        /// <param name="func_type">功能类型 100：插入操作  101：更新操作 102：删除操作</param>
        /// <param name="business_title">业务标题【用户管理】</param>
        /// <param name="detail">操作明细</param>
        public void AddOperationLog(OperationLogType func_type, BusinessTitleType business_title, string detail)
        {
            string clientIp = HttpHelper.GetIP();
            Task.Run(() =>
            {
                var userLoginInfo = GetLoginUserInfo();
                using (var con = PostgreDataBase.GetConnection(DatabaseName.PostgreSql_DB))
                {
                    SysOperationLogInfoEntity logInfoEntity = new SysOperationLogInfoEntity
                    {
                        business_title = business_title.GetEnumItemDescription(),
                        detail = detail,
                        func_type = (int)func_type,
                        ip_address = clientIp,
                        user_code = userLoginInfo.id,
                        user_name = userLoginInfo.name
                    };
                    var result = con.CommandSet<SysOperationLogInfoEntity>().InsertAsync(logInfoEntity);
                }
            });
        }


        /// <summary>
        /// 获取登录人员信息
        /// </summary>
        /// <returns></returns>
        public UserLoginInfo GetLoginUserInfo()
        {
            var resultInfo = new UserLoginInfo();
            try
            {
                string userId = HttpHelper.GetJwtUserId();
                string userStr = RedisClient.GetRedisDb(AuthorityRedisInfo.RedisDbWeb).StringGet(AuthorityRedisInfo.RedisSessionCode + userId);
                if (!string.IsNullOrEmpty(userStr))
                {
                    resultInfo = JsonHelper.JsonToObject<UserLoginInfo>(userStr);
                }
            }
            catch 
            {
                resultInfo.id = "18855C71C688CC68186A08D7C70C1CA3";
                resultInfo.name = "admin";
            }
            return resultInfo;
        }


    }
}
